package com.health.viewscontrols.medical.device.bo;

import android.bluetooth.BluetoothGatt;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.SpanUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.utils.HexUtil;
import com.health.R;
import com.health.httpbean.model.PoModel;
import com.health.tablebean.SBCL_DATA_NEW;
import com.health.viewscontrols.NovaApplication;
import com.health.viewscontrols.medical.base.BaseDeviceActivity;
import com.leadron.library.BODevicePodType;
import com.leadron.library.BO_POD;
import com.leadron.library.IOReaderSender;
import com.novabluetooth.data.DeviceShowSaveData;
import com.novabluetooth.services.BluetoothConstant;

import java.util.ArrayList;
import java.util.List;

/**
 * ChoiceMMed_C208S
 */
public class BOCmmActivity extends BaseDeviceActivity {

    public final static String UUID_SERVICE = "00001822-0000-1000-8000-00805f9b34fb";
    public final static String UUID_NOTIFY ="00002a5f-0000-1000-8000-00805f9b34fb";
    public final static String UUID_WRITE = "0000ffe2-0000-1000-8000-00805f9b34fb";

    BleDevice mBleDevice;
    private String mBloodOxygen;//血氧值
    private String mHeartRate;//心率值
    private String resultStringCH;//脉搏节律未见异常

    @Override
    public void startDevice() {
        showProgressDialog("正在搜索" + deviceEnum.getTitle() + "设备");
        if (mBleDevice == null) {
            if (false) {
                connectionPwBle();
            } else {
                BleManager.getInstance().scan(new BleScanCallback() {
                    @Override
                    public void onScanStarted(boolean success) {
                    }

                    @Override
                    public void onLeScan(BleDevice bleDevice) {
                        super.onLeScan(bleDevice);
                    }

                    @Override
                    public void onScanning(BleDevice bleDevice) {
                        if (bleDevice != null && bleDevice.getMac() != null && deviceEnum.getMac().equals(bleDevice.getMac())) {
                            connectionPwBle();
                        }
                    }

                    @Override
                    public void onScanFinished(List<BleDevice> scanResultList) {

                    }
                });
            }
        } else {
            ToastUtils.showShort("设备已连接，请等待测量结果");
            showProgressDialog("等待接收血氧数据");
        }
    }

    @Override
    public void doBusiness() {
        BleManager.getInstance().init(getApplication());

        tv_operation_tips.setText(com.nova.health.ble.R.string.bo_pc_C208S);

    }

    private void connectionPwBle() {
        BleManager.getInstance().connect(deviceEnum.getMac(), new BleGattCallback() {
            @Override
            public void onStartConnect() {
                blueToothState.setText("蓝牙开始连接");
                showProgressDialog("正在连接血氧设备");
            }

            @Override
            public void onConnectFail(BleDevice bleDevice, BleException exception) {
                Log.e(TAG, "onConnectFail: " +  exception.toString());
                blueToothState.setText("蓝牙连接失败");
                try {
                    BleManager.getInstance().cancelScan();
                    BleManager.getInstance().disconnectAllDevice();
                    connectionPwBle();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onConnectSuccess(final BleDevice bleDevice, BluetoothGatt gatt, int status) {
                //连接成功
                Log.e(TAG, "onConnectSuccess: " + bleDevice.getMac() );
                blueToothState.setText("蓝牙已连接");
                mBleDevice = bleDevice;
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getPwNotify(bleDevice);
                    }
                }, 500);

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        showResultState("");
                        release();
                    }
                }, 30 * 1000);
//                showProgressDialog("等待接收血氧数据");
                showProgressDialog("蓝牙连接成功，请测量30秒出结果");
            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
                blueToothState.setText("蓝牙已断开连接");
            }
        });
    }

    private void getPwNotify(final BleDevice bleDevice) {
        BleManager.getInstance().notify(bleDevice,
                UUID_SERVICE, UUID_NOTIFY,
                new BleNotifyCallback() {
                    @Override
                    public void onNotifySuccess() {
                        Log.e(TAG, "onNotifySuccess: " );
                    }

                    @Override
                    public void onNotifyFailure(BleException exception) {
                        Log.e(TAG, "onNotifyFailure: " +exception.toString());
                    }

                    @Override
                    public void onCharacteristicChanged(byte[] data) {
                        Log.e(TAG, "onCharacteristicChanged: "+ data );
                        //接收数据
                        String hexString = HexUtil.formatHexString(data);
                        Log.e(TAG, "onCharacteristicChanged: "+ hexString );
                        update(hexString);
                    }
                });
    }

    @Override
    public void update(String dataHex) {
        try {
            String cmd = dataHex.substring(14, 16);
            Log.e(TAG, "onCharacteristicChanged: " + dataHex + "    " + cmd );
//            String spo2 = dataHex.substring(4, 6) + dataHex.substring(2, 4);
//            String heart = dataHex.substring(8, 10) + dataHex.substring(6, 8);
//            int spo2Int = Integer.parseInt(spo2, 16);
//            int heartInt = Integer.parseInt(heart, 16);

//            Log.e(TAG, "接收数据: " + dataHex + "   spo2Int:" + spo2Int + " heartInt:" + heartInt );
            if ("00".equals(cmd)) {
                String spo2 = dataHex.substring(4, 6) + dataHex.substring(2, 4);
                String heart = dataHex.substring(8, 10) + dataHex.substring(6, 8);
                int spo2Int = Integer.parseInt(spo2, 16);
                int heartInt = Integer.parseInt(heart, 16);
                mBloodOxygen = spo2Int + "";
                mHeartRate = heartInt + "";
                showMsg(mBloodOxygen, mHeartRate);
                showMsg(spo2Int + "", heartInt + "");
                Log.e(TAG, "接收数据: " + dataHex + "   spo2Int:" + spo2Int + " heartInt:" + heartInt );
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setStatusPre() {
//        tv_state.setText("获取测量结果成功");
        tv_result.setText("脉率:" + mHeartRate + "bpm\t\t" + "血氧:" + mBloodOxygen + "%");
        Log.e(TAG, "setStatusPre: " + mBloodOxygen + "/" + mHeartRate);
        if (!TextUtils.isEmpty(mBloodOxygen)) {
            DeviceShowSaveData.getDataShow(mBloodOxygen + "/" + mHeartRate, BluetoothConstant.XUEYANG_LIKANG_KRK);
        }
    }

    @Override
    public void disconnectDevice() {
        try {
            BleManager.getInstance().cancelScan();
            if (mBleDevice != null) BleManager.getInstance().disconnect(mBleDevice);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    void showMsg(String nSpO2, String nPR) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mBloodOxygen = nSpO2;
                mHeartRate = nPR;
                tv_state.setText("实时测量数据：");
                tv_result.setText("脉率:" + mHeartRate + "bpm\t\t" + "血氧:" + mBloodOxygen + "%");
            }
        });
    }

    private void showResultState(String resultStringCH) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                cancelProgressDialog();
                tv_state.setText("测试结果:" + resultStringCH);
                tv_result.setText("脉率:" + mHeartRate + "bpm\t\t" + "血氧:" + mBloodOxygen + "%");
                Log.e(TAG, "setStatusPre: " + mBloodOxygen + "/" + mHeartRate);
                if (!TextUtils.isEmpty(mBloodOxygen)) {
                    DeviceShowSaveData.getDataShow(mBloodOxygen + "/" + mHeartRate, BluetoothConstant.XUEYANG_LIKANG_KRK);
                    PoModel poModel = new PoModel();
                    poModel.setBloodOxygenSaturation(mBloodOxygen + "");
                    poModel.setHeartRate(mHeartRate + "");
                    DeviceShowSaveData.saveXueyang(GsonUtils.toJson(poModel));
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        release();
        super.onDestroy();
    }

    private void release() {
        if (mBleDevice != null) {
            BleManager.getInstance().stopNotify(mBleDevice, UUID_SERVICE, UUID_NOTIFY);
            //断开设备
            BleManager.getInstance().disconnect(mBleDevice);
            mBleDevice = null;
        }
        try {
            BleManager.getInstance().cancelScan();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
